package com.ai.zhly.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;

import com.ai.dmc.index.base.impl.base.BaseServiceImpl;
import com.ai.dmc.index.base.sequence.SequenceGenerator;
import com.ai.dmc.index.common.InitParam;
import com.ai.dmc.index.common.bean.AreaBean;
import com.ai.dmc.index.common.bean.JobBean;
import com.ai.dmc.index.common.bean.StaffSessBean;
import com.ai.dmc.index.common.bean.UserBean;
import com.ai.dmc.index.common.cache.AreaCache;
import com.ai.dmc.index.common.exception.BusinessException;
import com.ai.dmc.index.common.util.CryptionUtil;
import com.ai.dmc.utils.json.JsonUtil;
import com.ai.frame.bean.InputObject;
import com.ai.frame.bean.OutputObject;
import com.ai.frame.logger.Logger;
import com.ai.frame.logger.LoggerFactory;
import com.github.pagehelper.Page;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * 
* @Title: MapDataImpl.java
* @Description: 家装宽带展示层service
* @author xueyf3  
* @date 2016年5月23日 下午4:22:54
* Copyright：Copyright (c) 2016
* Company：北京亚信智慧数据科技有限公司
* @version V1.0
 */
@SuppressWarnings({ "unused", "rawtypes", "unchecked" })
public class SysManagerServiceImpl extends BaseServiceImpl implements ISysManagerService{
	// 定义对应Mapper文件的命名空间
    private static final String NAMESPACE = "SysManager.";
    
    public static Logger log = LoggerFactory.getServiceLog(SysManagerServiceImpl.class);

    private SequenceGenerator sequenceGenerator;
    
    private ICommonService commonService;

    public void setSequenceGenerator(SequenceGenerator sequenceGenerator) {
        this.sequenceGenerator = sequenceGenerator;
    }
    

	public void setCommonService(ICommonService commonService) {
		this.commonService = commonService;
	}
   private SqlSession sqlSession;
	
	
	public SqlSession getSqlSession() {
		return sqlSession;
	}

	public void setSqlSession(SqlSession sqlSession) {
		this.sqlSession = sqlSession;
	}
	@Autowired  
	private HttpSession session;  
	  
	@Autowired  
	private HttpServletRequest request; 
//初始化
	private static final long serialVersionUID = 1656727829005434802L;
	private StaffSessBean staffSessBean;

	/**
	 * 初始化
	 */

   //用户管理-返回用户列表
	
	public void queryUserList2(InputObject inputObject, OutputObject outputObject) throws BusinessException {
		JSONObject j = new JSONObject();
    	String curPage =inputObject.getParams().get( "curPage");
		String pageSize =inputObject.getParams().get( "pageSize");
		String keyword =inputObject.getParams().get( "keyword");

		List<UserBean> uList = this.getBaseDao().queryForList(
	            NAMESPACE + "queryUserList", inputObject.getParams(),UserBean.class);	
		// 关键字过滤
				if (null != keyword && keyword.length() > 0 && uList.size() > 0) {
					Iterator<UserBean> it = uList.iterator();
					while (it.hasNext()) {
						UserBean u = it.next();
						String uId = u.getUserId();
						String uName = u.getUserName();
						if (!uId.contains(keyword) && !uName.contains(keyword)) {
							it.remove();
						}
					}
				}
				// 数据处理
				j =toPage(uList, curPage, pageSize);
			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("result", null == j ? "" : JsonUtil.Object2Json(j));
	        outputObject.setObject(JsonUtil.Object2Json(resultMap));	
		}
	
	//用户管理-返回用户列表
	    @Override
		public void queryUserList(InputObject inputObject, OutputObject outputObject) throws BusinessException {
	    	Map<String, Object> resultMap = new HashMap<String, Object>();
	    	String curPage =inputObject.getParams().get( "curPage");
			String pageSize =inputObject.getParams().get( "pageSize");
			String keyword =inputObject.getParams().get( "keyword");

			int curPageNum = Integer.valueOf(curPage);
			int pageSizeNum = Integer.valueOf(pageSize);
			String orderBy = "admin_time desc";
			//用户分页，如果是vertica数据库，特殊处理
			if ("vertica".equals(InitParam.DB_TYPE)) {
				int start = (Integer.valueOf(curPage)-1) * Integer.valueOf(pageSize) ;
				int end = Integer.valueOf(curPage) * Integer.valueOf(pageSize) ;
				inputObject.getParams().put("start", String.valueOf(start));
				inputObject.getParams().put("end", String.valueOf(end));
				String count = (String) this.getBaseDao().queryForObject(NAMESPACE+"queryUserListCount", inputObject.getParams());
				List<UserBean> userData = this.getBaseDao().queryForList(NAMESPACE+"queryUserListVertica", inputObject.getParams(),UserBean.class);
				Map<String, Object> map=new HashMap<String, Object>();
			    map.put("data",JsonUtil.Object2Json(userData));
			    map.put("pageSize", pageSize);
			    map.put("curPage", curPage);
			    map.put("totalPage", Integer.valueOf(count)/Integer.valueOf(pageSizeNum)+1);
			    map.put("totalNumber",  count);
			    JSONObject obj = JSONObject.fromObject(map);
				resultMap.put("result", null == obj ? "" : JsonUtil.Object2Json(obj));
		        outputObject.setObject(JsonUtil.Object2Json(resultMap));	
			}else {
				Page<Map<String, String>> page = (Page<Map<String, String>>) this.getBaseDao().queryForPage(NAMESPACE+"queryUserList", inputObject.getParams(), curPageNum, pageSizeNum, orderBy);
				Map<String, Object> map=new HashMap<String, Object>();
			    map.put("data",page.getResult());
			    map.put("pageSize", pageSize);
			    map.put("curPage", curPage);
			    map.put("totalPage", page.getPages());
			    map.put("totalNumber",  page.getTotal());
			    JSONObject obj = JSONObject.fromObject(map);
				resultMap.put("result", null == obj ? "" : JsonUtil.Object2Json(obj));
		        outputObject.setObject(JsonUtil.Object2Json(resultMap));	
			}
			
	 }

   //用户新增--地市列表
	@Override
	public void queryAreaTree(InputObject inputObject, OutputObject outputObject) throws BusinessException {	
	   String areaId= inputObject.getParams().get("areaId");
	   String isAdmin= inputObject.getParams().get("isAdmin");
		JSONArray jArr =new CommonServiceImpl().queryAreaTree(areaId,Boolean.parseBoolean(isAdmin));
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("result", null == jArr ? "" : jArr);
        outputObject.setObject(JsonUtil.Object2Json(resultMap));	
	}
	//返回要修改的用户信息
	@Override
    public void modifyUser(InputObject inputObject, OutputObject outputObject) {
		String userId=inputObject.getParams().get("userId2");
		inputObject.getParams().put("userId",userId);
		List<UserBean> u = this.getBaseDao().queryForList(
	            NAMESPACE + "queryUserByID", inputObject.getParams(),UserBean.class);
		List<JSONObject> rl = new ArrayList<JSONObject>();
		for (int i = 0; i < u.size(); i++) {
			String userName=u.get(i).getUserName();
			String userPassword=u.get(i).getUserPassword();
			String email=u.get(i).getEmail();
			String phone=u.get(i).getPhone();
			String status=u.get(i).getStatus();
			String areaId=u.get(i).getAreaId();
			String adminId=u.get(i).getAdminId();
			String adminName=u.get(i).getAdminName();
			String adminTime=u.get(i).getAdminTime();
			
			// 地市全量信息
			Map<String, AreaBean> allMap = (Map<String, AreaBean>) AreaCache.areaCache
					.get(AreaBean.TYPE_ALL);

			// 添加归属地市
			String areaName = allMap.get(areaId).getAreaName();

			
			JSONObject tmpObj = new JSONObject();
			tmpObj.put("userName",userName);
			tmpObj.put("userPassword",userPassword);
			tmpObj.put("email",email);
			tmpObj.put("phone",phone);
			tmpObj.put("status",status);
			tmpObj.put("areaId",areaId);
			tmpObj.put("areaName",areaName);
			tmpObj.put("adminId",adminId);
			tmpObj.put("adminName",adminName);
			tmpObj.put("adminTime",adminTime);

			rl.add(tmpObj);
		}

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("result", null == rl ? "" : JsonUtil.Object2Json(rl));
        outputObject.setObject(JsonUtil.Object2Json(resultMap));	
	}

	//新建用户
	@Override
	public void addSubmit(InputObject inputObject, OutputObject outputObject) throws BusinessException {
		Boolean flag=false;
		String userName=inputObject.getParams().get("userName");
		String userId2=inputObject.getParams().get("userId2");
		String email=inputObject.getParams().get("email");
		String phone=inputObject.getParams().get("phone");
		String status=inputObject.getParams().get("status");
		String areaId2=inputObject.getParams().get("areaId2");
		String adminId=inputObject.getParams().get("userId");
		String adminName=inputObject.getParams().get("userId");
		String userPwd = InitParam.DEFAULT_PWD;
//		userPwd = CryptionUtil.encrypt(userPwd);
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		String adminTime=df.format(new Date());
		Map map=new HashMap();
		map.put("adminId", adminId);
		map.put("adminName", adminName);
		map.put("adminTime", adminTime);
        map.put("userName",userName);
        map.put("email",email);
        map.put("phone",phone);
        map.put("status",status);
        map.put("areaId2",areaId2);
        map.put("userId",userId2);
        map.put("userPassword",userPwd);  
         List<UserBean> uList = this.getBaseDao().queryForList(
 	            NAMESPACE + "queryUserByID", map,UserBean.class);	
            if(uList!=null &&uList.size()>0){
			        outputObject.setObject(flag);
				}
			else{
				int rtn=0;
				try {
					rtn = this.getBaseDao().insert(
					        NAMESPACE + "addSubmit",map);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(rtn>0){
					flag= true;}
		        outputObject.setObject(flag);}	
         }
         
	
	
	//修改提交
	@Override
	public void submitModified(InputObject inputObject, OutputObject outputObject) throws BusinessException {
		Boolean flag = false;
		String userName=inputObject.getParams().get("userName");
		String userId2=inputObject.getParams().get("userId2");
		String email=inputObject.getParams().get("email");
		String phone=inputObject.getParams().get("phone");
		String status=inputObject.getParams().get("status");
		String areaId2=inputObject.getParams().get("areaId2");
		String adminId=inputObject.getParams().get("userId");
		String adminName=inputObject.getParams().get("userId");
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		String adminTime=df.format(new Date());
		Map map=new HashMap();
		map.put("adminId", adminId);
		map.put("adminName", adminName);
		map.put("adminTime", adminTime);
        map.put("userName",userName);
        map.put("email",email);
        map.put("phone",phone);
        map.put("status",status);
        map.put("areaId2",areaId2);
        map.put("userId",userId2);
		int i=0;
		try {
			i = this.getBaseDao().update(NAMESPACE + "updateUserInfo",map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(i>0){flag=true;}
        outputObject.setObject(flag);
	}

		

	
	//Utilize
	/**
	 * 
	 * @Description : 将数据组织成分页数据
	 * @param data
	 * @param curPage
	 * @param pageSize
	 * @return
	 * @return JSONObject
	 * 
	 * @author : wucm
	 * @date : 2015年8月3日 下午3:10:21
	 * 
	 */
	public  JSONObject toPage(List data, String curPageParam,
			String pageSizeParam) {
		JSONObject result = new JSONObject();

		if (null == data) {
			data = new ArrayList();
		}

		int pageSize = pageSizeParam == null ? 100
				: Integer.parseInt(pageSizeParam);
		int curPage = curPageParam == null ? 1 : Integer.parseInt(curPageParam);

		// 总数据
		int total = data.size();// 总记录数
		int totalPage = total % pageSize == 0 ? total / pageSize
				: total / pageSize + 1;
		if (totalPage == 0) {
			totalPage++;
		}

		// 当前页不大于总页数
		if (curPage > totalPage) {
			curPage = totalPage;
		}

		// 分页数据
		int start = (curPage - 1) * pageSize;
		int max = start + pageSize > total ? total : start + pageSize;
		List curList = new ArrayList();
		for (int i = start; i < max; i++) {
			if (null == data.get(i)) {
				continue;
			}
			curList.add(data.get(i));
		}
		net.sf.json.JSONArray curData = net.sf.json.JSONArray
				.fromObject(curList);

		result.put("totalPage", totalPage);
		result.put("totalNumber", total);
		result.put("data", curData);
		result.put("curPage", curPage);
		result.put("pageSize", pageSize);

		return result; }

	//删除用户记录
	@Override
	public void userDeleteSubmit(InputObject inputObject, OutputObject outputObject) throws BusinessException {
		Boolean flag=false;
		String userId=inputObject.getParams().get("userId2");
		Map map=new HashMap();
		map.put("userIds",userId);
		int i=0;
		try {
			i = this.getBaseDao().delete(NAMESPACE + "deleteUserInfo",map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(i>0){flag=true;}
        outputObject.setObject(flag);
	}


	@Override
	public void resetPwdSubmit(InputObject inputObject, OutputObject outputObject) throws BusinessException {
		Boolean flag=false;
		String userId=inputObject.getParams().get("userId2");
		// 获取默认重置密码
		String defaultPwd = InitParam.DEFAULT_PWD;
//		defaultPwd = CryptionUtil.encrypt(defaultPwd);
		Map map=new HashMap();
		map.put("userId", userId);
		map.put("defaultPWD", defaultPwd);

		int i=0;
		try {
			i = this.getBaseDao().update(NAMESPACE + "resetPwdSubmit",map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(i>0){flag=true;}
        outputObject.setObject(flag);
	}

  //角色列表
	@Override
	public void queryJobList(InputObject inputObject, OutputObject outputObject) throws BusinessException {
		JSONObject j = new JSONObject();
    	String curPage =inputObject.getParams().get( "curPage");
		String pageSize =inputObject.getParams().get( "pageSize");
		String keyword =inputObject.getParams().get( "keyword");
		List<JobBean> uList = this.getBaseDao().queryForList(
	            NAMESPACE + "queryJobList", inputObject.getParams(),JobBean.class);	
		// 关键字过滤
				if (null != keyword && keyword.length() > 0 && uList.size() > 0) {
					Iterator<JobBean> it = uList.iterator();
					while (it.hasNext()) {
						JobBean u = it.next();
						String uId = u.getJobId();
						String uName = u.getJobName();
						if (!uId.contains(keyword) && !uName.contains(keyword)) {
							it.remove();
						}
					}
				}
				// 地市全量信息
				Map<String, AreaBean> allMap = (Map<String, AreaBean>) AreaCache.areaCache
						.get(AreaBean.TYPE_ALL);

				// 添加归属地市
				Iterator<JobBean> it = uList.iterator();
				while (it.hasNext()) {
					JobBean u = it.next();
					String jaId = u.getAreaId();
					AreaBean ab = allMap.get(jaId);
					if (null != ab) {
						u.setAreaName(ab.getAreaName());
					}
				}
				// 数据处理
				j =toPage(uList, curPage, pageSize);
			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("result", null == j ? "" : JsonUtil.Object2Json(j));
	        outputObject.setObject(JsonUtil.Object2Json(resultMap));	
		}
	
	//角色查询
		@Override
		public void queryJob(InputObject inputObject, OutputObject outputObject) throws BusinessException {
			String jobId = inputObject.getParams().get("jobId");
			List<JobBean> rList = new ArrayList<>();
			List<JobBean> uList = this.getBaseDao().queryForList(
		            NAMESPACE + "queryJobList", inputObject.getParams(),JobBean.class);
			// 地市全量信息
			Map<String, AreaBean> allMap = (Map<String, AreaBean>) AreaCache.areaCache
					.get(AreaBean.TYPE_ALL);
			for (JobBean b:uList) {
				if (b.getJobId()!=null && b.getJobId().equals(jobId)) {
					rList.add(b);
				}
			}
			// 添加归属地市
			Iterator<JobBean> it = rList.iterator();
			while (it.hasNext()) {
				JobBean u = it.next();
				String jaId = u.getAreaId();
				AreaBean ab = allMap.get(jaId);
				if (null != ab) {
					u.setAreaName(ab.getAreaName());
				}
			}
			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("result", null == rList ? "" : JsonUtil.Object2Json(rList));
	        outputObject.setObject(JsonUtil.Object2Json(resultMap));	
			}


	@Override
	public void jobAdd(InputObject inputObject, OutputObject outputObject) throws BusinessException {
		Boolean flag=false;
		String jobId=inputObject.getParams().get("jobId");
		String jobName=inputObject.getParams().get("jobName");
		String areaId2=inputObject.getParams().get("areaId2");
		String jobRemark=inputObject.getParams().get("jobRemark");
		Map map=new HashMap();
		map.put("jobId", jobId);
		map.put("jobName", jobName);
		map.put("areaId2", areaId2);
        map.put("jobRemark",jobRemark); 
         List<JobBean> uList = this.getBaseDao().queryForList(
 	            NAMESPACE + "queryJobByID", map,JobBean.class);	
            if(uList!=null &&uList.size()>0){
			        outputObject.setObject(flag);
				}
			else{
				int rtn=0;
				try {
					rtn = this.getBaseDao().insert(
					        NAMESPACE + "jobAdd",map);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(rtn>0){
					flag= true;}
		        outputObject.setObject(flag);}	
		
	}

    //返回角色记录
	@Override
	public void modifyJob(InputObject inputObject, OutputObject outputObject) throws BusinessException {
		String jobId=inputObject.getParams().get("jobId");
		inputObject.getParams().put("jobId",jobId);
		Map map=new HashMap();
		map.put("jobId",jobId);
		List<JobBean> j = this.getBaseDao().queryForList(
	            NAMESPACE + "queryJobByID", map,JobBean.class);
		JSONArray data = JSONArray.fromObject(j);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("result", null == j ? "" : JsonUtil.Object2Json(j));
        outputObject.setObject(JsonUtil.Object2Json(resultMap));	
		
	}

    //提交角色信息
	@Override
	public void submitModifiedJob(InputObject inputObject, OutputObject outputObject) throws BusinessException {
		Boolean flag = false;
		String jobId=inputObject.getParams().get("jobId");
		String jobName=inputObject.getParams().get("jobName");
		String areaId2=inputObject.getParams().get("areaId2");
		String jobRemark=inputObject.getParams().get("jobRemark");
		Map map=new HashMap();
		map.put("jobId", jobId);
		map.put("jobName", jobName);
		map.put("areaId2", areaId2);
        map.put("jobRemark",jobRemark); 
		int i=0;
		try {
			i = this.getBaseDao().update(NAMESPACE + "submitModifiedJob",map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(i>0){flag=true;}
        outputObject.setObject(flag);
	}

	//删除角色记录
	@Override
	public void jobDeleteSubmit(InputObject inputObject, OutputObject outputObject) throws BusinessException {
			Boolean flag=false;
			String jobId=inputObject.getParams().get("jobId");
			Map map=new HashMap();
			map.put("jobIds",jobId);
			int i=0;
			try {
				i = this.getBaseDao().delete(NAMESPACE + "jobDeleteSubmit",map);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(i>0){flag=true;}
	        outputObject.setObject(flag);
		}
		
	}

	



